/**
 * © 2012 HaoTu.la
 */
if(typeof(comment) == 'undefined') comment = {};
var photo = {
	winScale: {width: 0, height: 0},
	gWidthPercent: 0.6,
	iWidthPercent: 1,
	boxOffset: {left:0, top:0, width:0, height:0},
	toolbox: {zoom:null, revolveL:null, revolveR:null, player:null},
	marginLeft: 20,
	currentSrc: '',
	total: 0,
	index: 0,
	isFirstLoadComment: true,
	comment: [],
	
	init: function() {
		this.marginLeft = $('.related').width() + 20;
		var self = this;
		$('.image a.display').click(function(){
			if(self._player.enable == false) {
				self._next();
			}
			return false;
		});
		$('.myplayer a').click(function(){
			if(self._player.enable == true) {
				self._player.stop();
			}
			return false;
		});
		$('.image span.previous').click(function(){self._previous();});
		$('.image span.next').click(function(){self._next();});
		this.resize();
		this._gallery();
		this._initToolBox();		
	},
	
	_initToolBox: function() {
		var self = this;
		this.toolbox.zoom = $('.toolbox').find('a.zoom').click(function(){
			$('.zoomPanel .zoomBox').css({'width': self.winScale.width + 'px', 'height': self.winScale.height + 'px'});
			$('.zoomMask').show();
			$('.zoomPanel').click(function(){
				$(this).fadeOut('slow');
				$('.zoomMask').hide();
			}).fadeIn('slow', function(){
				var zp = $(this);
				zp.find('code a').click(function(){
					zp.fadeOut('slow');
					$('.zoomMask').hide();
					return false;
				});
			}).find('img.zoomImg').attr('src', self.currentSrc);
			return false;
		});
		this.toolbox.revolveL = $('.toolbox').find('a.revolve-l').click(function(){
			var img = self._getImage().attr('id');
			$('#' + img).rotateLeft();
			self.resize(true);
			return false;
		});
		this.toolbox.revolveR = $('.toolbox').find('a.revolve-r').click(function(){
			var img = self._getImage().attr('id');
			$('#' + img).rotateRight();
			self.resize(true);
			return false;
		});
		this.toolbox.player = $('.toolbox').find('a.player').click(function(){
			if($(this).attr('_status') == 'playing') {
				self._player.stop();
			} else {
				self._player.start();
			}
			return false;
		});
	},
	
	_imgMouseOver: function() {
		$('.toolbox').fadeIn('slow');
		$('.share').fadeIn('slow');
	},
	
	_imgMouseOut: function() {
		$('.toolbox').fadeOut('slow');
		$('.share').fadeOut('slow');
	},
	
	_next: function() {
		index = this.index + 1;
		if(index > this.total - 1) {
			if(this._player.enable == true) {
				index = 0;
			} else {
				this._loading(true);
				//alert('ending');
				window.location.href = $('li.next a').attr('href');
				return false;			
			}
		}
		this._show(index);
	},
	
	_previous: function() {
		index = this.index - 1;
		if(index < 0) {
			if(this._player.enable == true) {
				index = this.total - 1;
			} else {
				this._loading(true);
				//alert('begining');
				window.location.href = $('li.prev a').attr('href');
				return false;				
			}
		}
		this._show(index);
	},
	
	_comment: function() {
		var href = $('#gallery li').eq(this.index).find('.img a').attr('href');
		var id = parseInt(href.substring(href.lastIndexOf('/') + 1, href.lastIndexOf('.')));
		$('input[name=id]').val(id);
		for(var i in comment.params) {
			if(/^id=[^\&]*/i.test(comment.params[i])) {
				comment.params[i] = 'id=' + id;
			}
		}
		var self = this;
		comment.postFunc = function() {
			if(typeof(self.comment[id]) != 'undefined') {
				self.comment[id] = undefined;
			}
		};	
		comment.reset($('#commentButton'));
		if(typeof(this.comment[id]) == 'undefined') {
			if(this.isFirstLoadComment == false) {
				comment.data = [];
				comment.load(1);
			}
			this.comment[id] = comment.data;
		} else {
			comment.data = this.comment[id];
			comment.load(1, false);
		}
	},
	
	_show: function(index) {
		if(typeof(index) == 'undefined') {
			index = 0;
			$('#gallery li').each(function(i){
				if($(this).attr('class') == 'current') {
					index = i;
				}
			});
		}
		this.index = index;
		this._containerWidth(true);
		this._npshow();
		this._slideToIndex();
		this._comment();
		$('h1 em').text('(' + (this.index + 1) + '/' + this.total + ')');		
		$('#gallery li.current')
				.attr('class', 'o5')
				.mouseover(function(){$(this).attr('class', '');})
				.mouseout(function(){$(this).attr('class', 'o5');});
		var img = $('#gallery li').eq(this.index)
				.unbind('mouseover').unbind('mouseout')
				.attr('class', 'current')
				.find('img.cache');
		var self = this;
		var sImage = this._getImage();
		this.currentSrc = sImage.attr('src');
		var id = 'img-' + Math.random().toString().replace('.', '_');
		$('a.display').html('').append('<img src="' + this.currentSrc + '" id="' + id + '" class="o9" />');
		
		if(img.attr('_complete') != 'true') {
			this._loading(true);
			img.attr('src', img.attr('rel')).load(function(){
				$(this).attr('_complete', 'true');
				self._imgFadeInComplete(img);
				$('.xloading').hide();
			});
		} else {
			this._imgFadeInComplete(img);
		}
	},
	
	_imgFadeInComplete: function(img) {
		var self = this;
		this.currentSrc = img.attr('src');
		this._getImage().fadeOut('fast', function(){
			$(this).attr('src', img.attr('src')).fadeIn('slow', function(){
				self.isFirstLoadComment = false;
				$('.processbar').css({'width': '0px'});
				self._player.play();
			});
		});
	},
	
	_loading: function(s) {
		if(s) {
			var cw = $('.comment').width();
			var ml = $('.realted').width();
			var l = ((this.winScale.width - ml - cw) / 2) + ml;
			$('.xloading').css({'left': l + 'px', 'margin-left': '0px'}).show();			
		} else {
			$('.xloading').hide();
		}
	},
	
	_slideToIndex: function() {
		var w = this._getData();
		var ml = Math.abs(w.marginLeft);
		var reLeftWidth = w.indexWidth - ml + w.indexLiWidth;
		var midWidth = w.containerWidth / 2;
		if(reLeftWidth > midWidth) {
			var sw = reLeftWidth - midWidth +  ml;
			if(sw > w.ulWidth - w.containerWidth) {
				sw = w.ulWidth - w.containerWidth;
			}
			this._slideRightButton(sw);
			return false;
		}
		reLeftWidth = reLeftWidth - w.indexLiWidth;
		if(midWidth > reLeftWidth) {
			var sw = ml - (midWidth - reLeftWidth) + w.indexLiWidth;
			if(sw <= 0) {
				sw = 0;
			}
			this._slideLeftButton(sw);
			return false;
		}
	},
	
	_slideLeftButton: function(sw) {
		var self = this;
		if(typeof(sw) == 'undefined') {
			sw = 0;
			var w = this._getData();
			if(Math.abs(w.marginLeft) > w.containerWidth) {
				sw = Math.abs(w.marginLeft) - w.containerWidth;
			}
		}
		$('#gallery ul').stop().animate({'margin-left': (- sw) + 'px'}, function(){self._npshow();});
		return false;
	},
	
	_slideRightButton: function(sw) {
		var self = this;
		if(typeof(sw) == 'undefined') {
			var w = this._getData();
			var lw = w.ulWidth - Math.abs(w.marginLeft) - w.containerWidth;
			sw = w.containerWidth + Math.abs(w.marginLeft);
			if(lw < w.containerWidth) {
				sw = Math.abs(w.marginLeft) + lw;
			}
		}
		$('#gallery ul').stop().animate({'margin-left': (- sw) + 'px'}, function(){self._npshow();});
		return false;
	},
	
	_npshow: function() {
		var self = this;
		var w = this._getData();
		if(w.marginLeft < 0) {
			$('#gallery a.leftButton').show().click(function(){return self._slideLeftButton();});
		} else {
			$('#gallery a.leftButton').unbind('click').hide();
		}
		if(w.ulWidth - Math.abs(w.marginLeft) > w.containerWidth) {
			$('#gallery a.rightButton').show().click(function(){return self._slideRightButton();});
		} else {
			$('#gallery a.rightButton').unbind('click').hide();
		}
	},
	
	_gallery: function() {
		var w = 0, self = this;
		this.index = 0;
		this.total = $('#gallery li').length;
		$('#gallery li').each(function(i){
			if($(this).attr('class') == 'current') {
				self.index = i;
			} else {
				$(this).mouseover(function(){$(this).attr('class', '');})
						.mouseout(function(){$(this).attr('class', 'o5');});
			}
			w += $(this).width();
			var img = $(this).find('.img img').attr('src');
			var ext = img.substring(img.lastIndexOf('.'));
			var src = img.substring(0, img.lastIndexOf('/')) + '/large' + ext;
			$('<img src="#" rel="' + src + '" class="cache" />').appendTo($(this));
			$(this).find('.img a').click(function(){
				if(self._player.enable == false) {
					self._show(i);
				}
				return false;
			});
		});
	},
	
	_containerWidth: function(notAnimate) {
		var w = this._getData();
		var mw = this.winScale.width * this.gWidthPercent;
		if(w.ulWidth > mw) {
			w.ulWidth = mw;
		}
		if(typeof(notAnimate) == 'undefined') {
			var self = this;
			$('#gallery .container').stop().animate({'width': w.ulWidth + 'px'}, 'slow', function(){
				self._show();
			});
		} else {
			$('#gallery .container').css({'width': w.ulWidth + 'px'});
		}
	},
	
	_getData: function() {
		var w1 = 0, w = 0;
		var index = this.index;
		var iWidth = 0;
		$('#gallery li').each(function(i){
			var _w = $(this).width();
			w += _w;
			if(i < index) {
				w1 += _w;
			}
			if(i == index) {
				iWidth = _w;
			}
		});
		var cw = parseInt($('#gallery .container').width());
		var ml = parseInt($('#gallery ul').css('margin-left').replace('px', ''));
		return {'ulWidth': w, 'indexWidth': w1, 'containerWidth': cw, 'marginLeft': ml, 'indexLiWidth': iWidth};
	},
	
	_getImage: function() {
		var link = $('a.display');
		var img = link.find('img');
		if(img.length == 0) {
			img = link.find('canvas');
		}
		return img.attr('id', 'img-' + Math.random().toString().replace('.', '_'));
	},
	
	/**
	 * 播放器
	 */
	_player: {
		enable: false,
		timer: null,
		speed: 3000,
		
		/**
		 * 停止
		 */
		stop: function() {
			clearTimeout(this.timer);
			this.enable = false;
			$('.image span.previous').show();
			$('.image span.next').show();
			$('.myplayer').hide();
			$('.processbar').stop().css({'width': '0px'});
			this.getPhoto().toolbox.player.attr('class', 'player play').attr('_status', 'pause');
			this.getPhoto()._imgMouseOver(true);
		},
		
		/**
		 * 开始
		 */
		start: function() {
			this.enable = true;
			$('.image span.previous').hide();
			$('.image span.next').hide();
			$('.myplayer').show();
			this.getPhoto().toolbox.player.attr('class', 'player pause').attr('_status', 'playing');
			this.getPhoto()._imgMouseOut();
			this.getPhoto()._next();
		},
		
		play: function() {
			if(this.enable == true) {
				var self = this;
				this.timer = setTimeout(function(){self.start();}, self.speed);
				$('.processbar').animate({'width': '100%'}, self.speed);
			}
		},
		
		getPhoto: function() {
			return photo;
		}
	},
	
	keydown: function(e) {
		if(e.keyCode == 27) {
			this._player.stop();
		}
		if(e.keyCode == 37 || e.keyCode == 38) {
			if(this._player.enable == false) {
				this._previous();
			}
			return false;
		}
		if(e.keyCode == 39 || e.keyCode == 40) {
			if(this._player.enable == false) {
				this._next();
			}
			return false;
		}
		return true;
	},
	
	mousedown: function(e) {
		//this._player.stop();
		return true;
	},
	
	mousemove: function(e) {
		if(this._player.enable == true) {
			return false;
		}
		var x = e.clientX;
		var y = e.clientY;
		
		var l = this.boxOffset.left;
		var t = this.boxOffset.top;
		var r = this.boxOffset.width + l;
		var b = this.boxOffset.height + t;
		if(x >= l && y >= t && x <= r && y <= b) {
			this._imgMouseOver();
		} else {
			this._imgMouseOut();
		}		
	},
	
	resize: function(notShow) {
		this.winScale = {width: $(window).width(), height: $(window).height()};
		var npWd = $('.comment').width();
		var maxW = this.winScale.width * this.iWidthPercent - npWd - this.marginLeft;
		var maxH = this.winScale.height - $('.image').offset().top - $('.gmask').height() - $('#fbmask').height();
		var imgBox = $('.image').css({'width': maxW + 'px', 'height': maxH + 'px', 'left': this.marginLeft + 'px'});
		$('.image div.imgBox').css({'width': maxW + 'px', 'height': maxH + 'px'});
		this._getImage().stop().animate({'max-width': (maxW - 20) + 'px','max-height': (maxH - 20) + 'px'}, 'slow');
		var offset = imgBox.offset();
		$('.share').css({'left': offset.left + 'px', 'top': (offset.top + 12) + 'px'});
		this.boxOffset = {left:offset.left, top:offset.top, width:imgBox.width(), height:imgBox.height()};
		$('#gallery').css({'width': (this.winScale.width + this.marginLeft - npWd) + 'px'});
		$('h1').css({'width': (this.winScale.width + this.marginLeft - npWd) + 'px'});
		$('.related .relatedBox').css({'height': (maxH - 36) + 'px'});
		$('.comment').css({'height': maxH + 'px'});
		$('#commentMain').css({'height': (maxH - 138) + 'px'});
		if(typeof(notShow) == 'undefined') {
			this._containerWidth();			
		}
	}
	
};

$(document).ready(function(){photo.init();}).mousemove(function(e){photo.mousemove(e);});
$(window).resize(function(){photo.resize(true);})
		.keydown(function(e){return photo.keydown(e);})
		.mousedown(function(e){return photo.mousedown(e);});
